package com.example.adapter

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.example.R
import com.example.diary.DiaryDetailActivity
import com.example.model.Diary

class DiaryRecyclerAdapter(val activity: FragmentActivity?, var diaryList: ArrayList<Diary>):
    RecyclerView.Adapter<DiaryRecyclerAdapter.DiaryViewHolder>() {

    // 视图固定器
    inner class DiaryViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        // 标题文本控件
        val diaryTitle: TextView = view.findViewById(R.id.diary_title)
        // 内容文本控件
        val diaryDescription: TextView = view.findViewById(R.id.diary_description)
    }

    override fun getItemCount() = diaryList.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DiaryViewHolder {
        val view: View = LayoutInflater.from(parent.context)
            .inflate(R.layout.diary_item, parent, false)
        val viewHolder = DiaryViewHolder(view)
        // item点击事件
        viewHolder.itemView.setOnClickListener {
            val position = viewHolder.adapterPosition
            val diary = diaryList[position]
            val id = diary.id
            val intent = Intent(activity, DiaryDetailActivity::class.java)
            intent.putExtra("id", id)
            activity?.startActivity(intent)
        }
        return viewHolder
    }

    override fun onBindViewHolder(holder: DiaryViewHolder, position: Int) {
        val diary: Diary = diaryList[position]
        holder.diaryTitle.text = diary.title
        holder.diaryDescription.text = diary.description
    }
}